﻿using Admin.NET.Application.Service.AGV.Task.DTO;
using Admin.NET.Application.Service.AGV.V2.Task.DTO;
using Admin.NET.Application.Service.EG_AGV_Task.DTO;
using Admin.NET.Application.Util;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;

namespace Admin.NET.Application.Service.EG_AGV_Task
{
    [ApiDescriptionSettings("AGV模块接口V3.0", Name = "AGV相关接口", Order = 100)]
    public class TaskService : IDynamicApiController, ITransient
    {
        private static readonly DHRequester _DHRequester = new DHRequester();
        private static readonly HttpClient _HttpClient = new HttpClient();

        #region 关系注入
        private readonly SqlSugarRepository<TaskEntity> _TaskEntity = App.GetService<SqlSugarRepository<TaskEntity>>();
        private readonly SqlSugarRepository<TaskDetailEntity> _TaskDetailEntity = App.GetService<SqlSugarRepository<TaskDetailEntity>>();
        private readonly SqlSugarRepository<TemLogicEntity> _TemLogicEntity = App.GetService<SqlSugarRepository<TemLogicEntity>>();
        private readonly SqlSugarRepository<InfoEntity> _InfoEntity = App.GetService<SqlSugarRepository<InfoEntity>>();
        private readonly SqlSugarRepository<InfoAgvEntity> _InfoAgvEntity = App.GetService<SqlSugarRepository<InfoAgvEntity>>();
        private readonly SqlSugarRepository<AlarmEntity> _AlarmEntity = App.GetService<SqlSugarRepository<AlarmEntity>>();

        #endregion

        #region 任务下达 *

        /// <summary>
        /// 下达任务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/AddItemAsync")]
        [AllowAnonymous]
        public async Task AddAsync(AddDTO input)
        {
            try
            {
                #region 请求数据验证
                if (string.IsNullOrEmpty(input.TemplateNo))
                {
                    throw Oops.Oh($"请传入任务模版编号！");
                }

                if (string.IsNullOrEmpty(input.TaskDetail[0].Positions))
                {
                    throw Oops.Oh($"请传入运行的点位信息！");
                }
                #endregion
                TaskEntity taskEntity = input.Adapt<TaskEntity>();
                taskEntity.TaskPath = input.TaskDetail[0].Positions;
                taskEntity.AGVNo = input.TaskDetail[0].AgvNo;
                taskEntity.ModelNo = input.TemplateNo;
                await AddAsync(taskEntity);
            }
            catch (Exception ex)
            {
                throw Oops.Oh($"{ex.Message}");
            }
        }

        public async Task<DHMessage> AddAsync(TaskEntity taskEntity)
        {
            // 查询是否有传入的模板
            var temLogItem = _TemLogicEntity.GetFirst(p => p.TemLogicNo == taskEntity.ModelNo);
            if (temLogItem == null || string.IsNullOrEmpty(temLogItem.TemLogicNo))
            {
                throw Oops.Oh($"未找到对应的任务模版！");
            }
            // 得到任务点位数
            var positions = taskEntity.TaskPath.Split(',');
            if (taskEntity.Id == 0) taskEntity.Id = SnowFlakeSingle.Instance.NextId();
            taskEntity.TaskNo = taskEntity.TaskNo ?? taskEntity.Id.ToString();
            taskEntity.CreateTime = DateTime.Now;
            taskEntity.UpdateTime = DateTime.Now;
            taskEntity.Source = taskEntity.Source ?? "手工下发";
            // TODO:测试是否需要修改
            taskEntity.TaskState = 0;
            if (taskEntity.Priority == 0) taskEntity.Priority = 2;
            taskEntity.TaskName = taskEntity.TaskName ?? temLogItem.TemLogicName;
            var taskDetailList = positions.Select(t => new TaskDetailEntity
            {
                TaskID = taskEntity.Id,
                TaskPath = t,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now
            }).ToList();
            DHMessage dHMessage = await _DHRequester.AddTaskAsync(taskEntity);
            if (dHMessage.code == 500)
            {
                throw Oops.Oh($"{dHMessage.desc}");
            }
            //var nowTaskItemJsonString = JsonConvert.SerializeObject(input);
            var item = await _TaskEntity.InsertAsync(taskEntity); //任务主表
            await _TaskDetailEntity.InsertOrUpdateAsync(taskDetailList); //任务详细
            return dHMessage;
        }

        #endregion

        #region 追加点位
        /// <summary>
        /// 追加点位信息
        /// </summary>
        /// <param name="input"> </param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/AppendAsync")]
        public async Task AppendAsync(AppendAsyncDTO input)
        {
            //var para = JsonConvert.SerializeObject(dto);
            //_ = FileUtil.DebugTxt("V2.0 AppendAsync", MessageTypeEnum.记录, para, "", "追加点位信息");
            try
            {
                #region 请求数据验证
                //var temLogicNo = App.Configuration["RCS:TemLogicNo"];
                //if (string.IsNullOrEmpty(temLogicNo))
                //{
                //    throw new Exception("现场实施未在配置文件内配置对应的模版编号！");
                //}

                if (string.IsNullOrEmpty(input.taskNo))
                {
                    throw Oops.Oh($"任务编号必须传入！");
                }

                if (string.IsNullOrEmpty(input.positions))
                {
                    throw Oops.Oh($"点位信息必须传入！");
                }

                //if (string.IsNullOrEmpty(input.source))
                //{
                //    throw Oops.Oh($"来源必须传入！");
                //}
                #endregion

                #region 本地入库

                #endregion

                #region DH请求

                #endregion
            }
            catch (Exception ex)
            {
                //_ = FileUtil.DebugTxt(ex.Message, MessageTypeEnum.记录, para, ex.StackTrace, "新增任务Error");
                throw Oops.Oh(ex.Message);
            }
        }
        #endregion

        #region 变更任务点位
        /// <summary>
        /// 变更任务点位
        /// </summary>
        /// <param name="updateTaskPointDto"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/UpdateTaskPoint")]
        public async Task UpdateTaskPoint(UpdateTaskPointDto updateTaskPointDto)
        {
            //var para = JsonConvert.SerializeObject(updateTaskPointDto);
            try
            {
                if (string.IsNullOrEmpty(updateTaskPointDto.TaskNo))
                {
                    throw Oops.Oh($"必须传入需要变更的任务单号！");
                }
                if (string.IsNullOrEmpty(updateTaskPointDto.PointPath))
                {
                    throw Oops.Oh("必须传入点位信息！");
                }
                var taskItem = _TaskEntity.GetFirst(p => p.TaskNo == updateTaskPointDto.TaskNo);
                if (taskItem == null || string.IsNullOrEmpty(taskItem.TaskNo))
                {
                    throw Oops.Oh($"未找到{updateTaskPointDto.TaskNo}的任务单！");
                }
                var taskDetalList = _TaskDetailEntity.GetList(p => p.TaskID == taskItem.Id);
                if (taskDetalList != null && taskDetalList.Any())
                {
                    await _TaskDetailEntity.DeleteAsync(taskDetalList);
                }
                var paths = updateTaskPointDto.PointPath.Split(',');
                List<TaskDetailEntity> newTaskDetailList = new List<TaskDetailEntity>();
                foreach (var item in paths)
                {
                    TaskDetailEntity newTaskDetail = new TaskDetailEntity();
                    newTaskDetail.TaskPath = item;
                    newTaskDetail.TaskID = taskItem.Id;
                    newTaskDetailList.Add(newTaskDetail);
                }
                #region 调用DH
                DHMessage dHMessage = await _DHRequester.UpdateTaskAsync(updateTaskPointDto.TaskNo, updateTaskPointDto.PointPath);
                //_ = FileUtil.DebugTxt("DH返回信息", MessageTypeEnum.记录, JsonConvert.SerializeObject(dHMessage), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "V2.0任务变更请求记录");
                if (dHMessage.code == 500)
                {
                    throw Oops.Oh(dHMessage.desc);
                }
                #endregion

                await _TaskDetailEntity.InsertOrUpdateAsync(newTaskDetailList);
                //_ = FileUtil.DebugTxt("请求日志", MessageTypeEnum.记录, para, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "V2.0任务变更请求记录");

            }
            catch (Exception ex)
            {
                //_ = FileUtil.DebugTxt(ex.Message, MessageTypeEnum.错误, para, ex.StackTrace, "V2.0任务变更错误记录");
                throw Oops.Oh(ex.Message);
            }
        }
        #endregion

        #region 获取数据 *

        /// <summary>
        /// 分页查询任务单信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/PageAsync")]
        public async Task<SqlSugarPagedList<TaskEntity>> PageAsync(InDTO input)
        {
            try
            {
                DateTime? sTime = null;
                DateTime? eTime = null;

                if (input.CreateTime != null)
                {
                    sTime = Convert.ToDateTime(
                        $"{Convert.ToDateTime(input.CreateTime).ToString("yyyy-MM-dd")} 00:00:00");
                    eTime = Convert.ToDateTime(
                        $"{Convert.ToDateTime(input.CreateTime).ToString("yyyy-MM-dd")} 23:59:59");
                }
                var taskPageList = await _TaskEntity.AsQueryable()
                    .WhereIF(!string.IsNullOrWhiteSpace(input.AGVNo), u => u.AGVNo.Contains(input.AGVNo.Trim()))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.TaskName), u => u.TaskName.Contains(input.TaskName.Trim()))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.TaskNo), u => u.TaskNo.Contains(input.TaskNo.Trim()))
                    .WhereIF(!string.IsNullOrWhiteSpace(input.Source), u => u.Source.Contains(input.Source.Trim()))
                    .WhereIF(input.CreateTime != null, p => p.CreateTime >= sTime && p.CreateTime <= eTime)
                    .WhereIF(!string.IsNullOrWhiteSpace(input.TaskState), u => input.TaskState.Trim().Contains(u.TaskState.ToString()))
                    .OrderByDescending(p => p.Id)
                    .ToPagedListAsync(input.Page, input.PageSize);
                return taskPageList;
            }
            catch (Exception ex)
            {
                //_ = FileUtil.DebugTxt(ex.Message, MessageTypeEnum.错误, para, ex.StackTrace, "获取任务列表Error");
                throw Oops.Oh($"{ex.Message}");
            }
        }

        /// <summary>
        /// 获取任务信息
        /// </summary>
        /// <param name="taskNo"></param>
        /// <returns></returns>
        [HttpGet("/AGV/Task/GetItemAsync")]
        [AllowAnonymous]
        public async Task<TaskDTO> GetItemAsync(string taskNo)
        {
            //_ = FileUtil.DebugTxt("获取任务详细", MessageTypeEnum.记录, taskNo, "", "获取任务详细记录");
            //TaskDTO taskDto = new TaskDTO();
            try
            {
                if (string.IsNullOrEmpty(taskNo))
                {
                    throw Oops.Oh($"任务ID不可为空！");
                }
                TaskEntity taskItem = _TaskEntity.GetFirst(p => p.TaskNo == taskNo);
                TaskDTO taskDto = taskItem.Adapt<TaskDTO>();
                if (taskItem != null && !string.IsNullOrEmpty(taskItem.TaskNo))
                {
                    var dHMessage = await _DHRequester.GetTaskAsync(taskNo);
                    if (dHMessage.code == 500)
                    {
                        throw Oops.Oh($"{dHMessage.desc}");
                    }
                    // 转换成json格式
                    var daString = JsonConvert.SerializeObject(dHMessage.data);
                    // 反序列化将json格式转化成普通的c#对象
                    var da = JsonConvert.DeserializeObject<taskV2>(daString);

                    if (!string.IsNullOrEmpty(taskItem.AGVNo))
                    {
                        var infoItem = await _InfoEntity.GetFirstAsync(p => p.AgvNo == taskItem.AGVNo);
                        taskDto.AssetNumber = infoItem?.AssetNumber;
                    }
                    if (da.statusObj != null)
                    {
                        var detaiItem = JsonConvert.DeserializeObject<AcceptDTO>(da.statusObj.ToString());
                        //var detaiItem = da.taskOrderDetail[0];
                        taskDto.SubTaskSeq = detaiItem?.subTaskSeq;
                        taskDto.SubTaskStatus = detaiItem?.subTaskStatus;
                        taskDto.carStatus = detaiItem.status;
                        taskDto.AGVNo = detaiItem?.deviceNum;
                    }
                    taskItem.TaskState = taskDto.TaskState;
                    taskItem.SubTaskSeq = taskDto.SubTaskSeq;
                    await _TaskEntity.UpdateAsync(taskItem);
                }
                return taskDto;
            }
            catch (Exception ex)
            {
                //_ = FileUtil.DebugTxt(ex.Message, MessageTypeEnum.错误, taskNo, ex.StackTrace, "获取任务详细Error");
                throw Oops.Oh($"{ex.Message}");
            }
        }

        /// <summary>
        /// 任务单各状态数量汇总
        /// </summary>
        /// <param name="dateTime">汇总日期</param>
        /// <returns></returns>
        [HttpGet("/AGV/Task/SumTask")]
        public SumTaskDTO SumTask(DateTime dateTime)
        {
            SumTaskDTO sumTaskDto = new SumTaskDTO();
            //var taskList = _TaskEntity.SqlQueryAsync<TaskEntity>($"select * from agv_task where STR_TO_DATE({nameof(TaskEntity.CreatedTime)}, '%Y-%m-%d')='{dateTime.ToString("yyyy-MM-dd")}'").Result;
            // null：请求成功；1：未发送；2：正在取消；3：已取消；4：正在发送；5：发送失败；6：执行中；7：执行失败；8：任务完成；9：已下发;
            var taskList = _TaskEntity.GetList(p =>
                Convert.ToDateTime(p.CreateTime).ToString("yyyy-MM-dd") == dateTime.ToString("yyyy-MM-dd"));
            sumTaskDto.CancelQTY = taskList.Where(p => p.TaskState == 2 || p.TaskState == 3)?.Count() ?? 0;
            sumTaskDto.FailQTY = taskList.Where(p => p.TaskState == 5 || p.TaskState == 7)?.Count() ?? 0;
            sumTaskDto.FinisQTY = taskList.Where(p => p.TaskState == 8)?.Count() ?? 0;
            sumTaskDto.NotStartedQTY =
                taskList.Where(p => p.TaskState == null || p.TaskState == 9 || p.TaskState == 4 || p.TaskState == 1)
                    ?.Count() ?? 0;
            sumTaskDto.StartQTY = taskList.Where(p => p.TaskState == 6)?.Count() ?? 0;
            return sumTaskDto;
        }

        /// <summary>
        /// 获取 AGV 设备信息
        /// </summary>
        /// <param name="agvInfoDto">因为平台参数问题，传递的AgvNo需转换成设备序列号，才能查询</param>
        /// <returns></returns>
        [HttpPost("/AGV/Info/GetItemAsync")]
        [AllowAnonymous]
        public async Task<List<GetAgvInfoDto>> GetItemAsync(AgvInfoDto agvInfoDto)
        {
            try
            {
                if (string.IsNullOrEmpty(agvInfoDto.Area))
                {
                    throw Oops.Oh("区域id不能为空");
                }
                // 分割多个序列号
                string[] s = agvInfoDto.AgvNo.Split(",");
                string newAgvNum = "";
                for (int i = 0; i < s.Length; i++)
                {
                    // agv序列号
                    var agvData = _InfoAgvEntity.GetFirst(x => x.deviceName == s[i].ToString());
                    string agvCode = agvData.deviceCode;
                    if (s.Length == 1)
                    {
                        newAgvNum += agvCode;
                    }
                    else
                    {
                        newAgvNum += agvCode + ",";
                        // 删除最后一个逗号
                        if (s.Last() == agvData.deviceName)
                        {
                            newAgvNum = newAgvNum.TrimEnd(',');
                        }
                    }
                }
                agvInfoDto.AgvNo = newAgvNum;
                var dHMessage = await _DHRequester.GetAgvInfoAsync(agvInfoDto);
                if (dHMessage.code == 500)
                {
                    throw Oops.Oh($"{dHMessage.desc}");
                }
                var daString = JsonConvert.SerializeObject(dHMessage.data).Trim();
                // 将返回的数据序列化成DH参数集合
                List<DHAgvInfoDto> dHAgvInfoDtos = JsonConvert.DeserializeObject<List<DHAgvInfoDto>>(daString);
                List<GetAgvInfoDto> listAgvInfoDto = new List<GetAgvInfoDto>();
                GetAgvInfoDto getAgvInfo = new GetAgvInfoDto();
                for (int i = 0; i < dHAgvInfoDtos.Count; i++)
                {
                    // 将数组转换成字符串
                    var stringdata = dHAgvInfoDtos[i].devicePostionRec;
                    string stringpostionrec = "";
                    if (stringdata != null)
                    {
                        foreach (var item in stringdata)
                        {
                            stringpostionrec = item;
                        }
                    }
                    else
                    {
                        stringpostionrec = null;
                    }
                    getAgvInfo.AgvNo = dHAgvInfoDtos[i].deviceName;
                    getAgvInfo.DevId = dHAgvInfoDtos[i].deviceCode;
                    getAgvInfo.PayLoad = dHAgvInfoDtos[i].payLoad;
                    getAgvInfo.Position = dHAgvInfoDtos[i].devicePosition;
                    // TODO:不能直接转换成tostring
                    getAgvInfo.postionRec = stringpostionrec;
                    getAgvInfo.Battery = dHAgvInfoDtos[i].battery;
                    // TODO:返回的没有电池循环次数
                    getAgvInfo.BatteryCycle = null;
                    // TODO:返回的没有设备离线时间
                    getAgvInfo.offlineTime = null;
                    getAgvInfo.Status = dHAgvInfoDtos[i].deviceStatus;
                    listAgvInfoDto.Add(getAgvInfo);
                };
                return listAgvInfoDto;
            }
            catch (Exception ex)
            {

                throw Oops.Oh($"{ex.Message}");
            }
        }

        #endregion

        #region 增加任务模板

        /// <summary>
        /// 增加任务模板
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/AddTemLogicModel")]
        public async Task AddTemLogicModel(TemlogicModel input)
        {
            var model = input.Adapt<TemLogicEntity>();
            await _TemLogicEntity.InsertAsync(model);

        }

        #endregion

        #region 查询任务模板

        /// <summary>
        /// 查询任务模板
        /// </summary>
        /// <returns></returns>
        [HttpPost("/AGV/Task/GetTemLogicsAll")]
        public async Task<SqlSugarPagedList<TemLogicEntity>> GetTemLogicsAll(TemlogicPageModel input)
        {
            var data = _TemLogicEntity.AsQueryable()
                            .WhereIF(!string.IsNullOrEmpty(input.TemlogicName), it => it.TemLogicName.Contains(input.TemlogicName))
                            .WhereIF(!string.IsNullOrEmpty(input.TemLogicNo), it => it.TemLogicNo.Contains(input.TemLogicNo))
                            .WhereIF(input.HoldingPoint == 0, it => it.HoldingPoint == input.HoldingPoint)
                            .WhereIF(input.HoldingPoint == 1, it => it.HoldingPoint == input.HoldingPoint)
                            .Select(x => x);

            return await data.ToPagedListAsync(input.Page, input.PageSize);

        }


        #endregion

        #region 删除任务模板

        /// <summary>
        /// 删除任务模板
        /// </summary>
        /// <param name="num">任务模板编号</param>
        /// <param name="id">任务模板id</param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/DeleteTemLogic")]
        public async Task DeleteTemLogic(string? num, long? id)
        {
            var entity = await _TemLogicEntity.GetFirstAsync(x => x.TemLogicNo == num || x.Id == id);
            await _TemLogicEntity.FakeDeleteAsync(entity);
        }


        #endregion

        #region 更新任务模板

        /// <summary>
        /// 更新任务模板
        /// </summary>
        /// <returns></returns>
        [HttpPost("/AGV/Task/UpdateTemLogic")]
        public async Task UpdateTemLogic(UpdateTem input)
        {
            var entity = input.Adapt<TemLogicEntity>();
            await _TemLogicEntity.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();

        }

        #endregion

        #region 按条件模糊查询符合条件的任务模板

        /// <summary>
        /// 按条件模糊查询符合条件的任务模板
        /// </summary>
        /// <param name="num">任务模板编号</param>
        /// <param name="name">任务模板名称</param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/GetTemLogicsContains")]
        public List<TemLogicEntity> GetTemLogicsContains(string? num, string? name)
        {

            return _TemLogicEntity.AsQueryable()
                            .Where(x => x.TemLogicNo.Contains(num) || x.TemLogicName.Contains(name))
                            .ToList();

        }

        #endregion

        #region 取消、继续、完成 *
        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="cancelDTO"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/CancelAsync")]
        public async Task CancelAsync(CancelDTO cancelDTO)
        {
            if (cancelDTO == null || string.IsNullOrEmpty(cancelDTO.TaskNo))
            {
                throw Oops.Oh($"取消任务时未传入对应的任务ID！");
            }

            //var para = JsonConvert.SerializeObject(cancelDTO);
            //_ = FileUtil.DebugTxt("取消日志记录", MessageTypeEnum.记录, para, "", "V2.0取消日志记录");
            try
            {
                #region 调用DH接口
                var dHMessage = await _DHRequester.CancelTaskAsync(cancelDTO);
                if (dHMessage.code == 500)
                {
                    throw Oops.Oh($"{dHMessage.desc}");
                }
                #endregion

                #region 写本地库
                var taskList = _TaskEntity.GetList(p => p.TaskNo == cancelDTO.TaskNo);
                // var taskEntity = await _TaskEntity.FirstOrDefaultAsync(p => p.TaskNo == cancelDTO.TaskNo);
                foreach (var item in taskList)
                {
                    // 1：未发送；2：正在取消；3：已取消；4：正在发送；5：发送失败；6：执行中；7：执行失败；8：任务完成；9：已下发;
                    item.TaskState = 3;
                    item.UpdateTime = DateTime.Now;
                }
                await _TaskEntity.UpdateRangeAsync(taskList);
                #endregion
            }
            catch (Exception ex)
            {
                //_ = FileUtil.DebugTxt(ex.Message, MessageTypeEnum.记录, para, ex.StackTrace, "V2.0取消日志Error");
                throw Oops.Oh($"{ex.Message}");
            }
        }

        /// <summary>
        /// 继续任务
        /// 如已是最后一个点位，该任务会自动完成
        /// </summary>
        /// <param name="goOnAsyncDTO"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/GoOnAsync")]
        public async Task GoOnAsync(GoOnAsyncDTO goOnAsyncDTO)
        {
            //_ = FileUtil.DebugTxt("继续任务接口请求", MessageTypeEnum.记录, goOnAsyncDTO.taskNo, "", "继续任务记录");
            try
            {
                var dHMessage = await _DHRequester.GoOnTaskAsync(goOnAsyncDTO.taskNo);
                //_ = FileUtil.DebugTxt("DH返回信息", MessageTypeEnum.记录, goOnAsyncDTO.taskNo, JsonConvert.SerializeObject(dHMessage), "继续任务记录");
                if (dHMessage.code == 500)
                {
                    throw Oops.Oh(dHMessage.desc);
                }
                var taskList = _TaskEntity.GetList(p => p.TaskNo == goOnAsyncDTO.taskNo);
                foreach (var item in taskList)
                {
                    // 1：未发送；2：正在取消；3：已取消；4：正在发送；5：发送失败；6：执行中；7：执行失败；8：任务完成；9：已下发;
                    item.TaskState = 8;
                    item.UpdateTime = DateTime.Now;
                }
                await _TaskEntity.UpdateRangeAsync(taskList);
            }
            catch (Exception ex)
            {
                //_ = FileUtil.DebugTxt(ex.Message, MessageTypeEnum.错误, goOnAsyncDTO.taskNo, ex.StackTrace, "V1继续任务Error");
                throw Oops.Oh($"{ex.Message}");
            }
        }

        #endregion

        #region 接受RCS上报信息

        /// <summary>
        ///  接受RCS上报信息
        /// </summary>
        /// <param name="acceptDTO"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpPost("/AGV/Task/AcceptAsync")]
        [AllowAnonymous]
        [UnifyProvider("easygreat")]
        public async Task<string> AcceptAsyncNew(AcceptDTO acceptDTO)
        {
            try
            {
                // 查找是否有相同任务
                var item = await _TaskEntity.GetFirstAsync(u => u.TaskNo == acceptDTO.orderId);

                if (item == null)
                {
                    throw Oops.Oh($"未找到有对应{acceptDTO.orderId}编号的AGV任务");
                }
                // 任务执行的状态
                int AgvStatus = 0;
                string AgvStatusString = "";
                item.AGVNo = acceptDTO.deviceNum;
                // 已下发
                if (acceptDTO.status == 9)
                {
                    // 任务开始时间
                    item.STime = DateTime.Now;
                }
                // 任务结束时间
                // 3 已取消 5 发送失败 7 执行失败 8 已已完成
                if (acceptDTO.status == 3 || acceptDTO.status == 5 || acceptDTO.status == 7 || acceptDTO.status == 8)
                {
                    item.ETime = DateTime.Now;
                }
                // 任务失败的原因
                item.Message = acceptDTO.errorDesc;
                switch (acceptDTO.status)
                {
                    // 已取消
                    case 3:
                        AgvStatus = 3;
                        AgvStatusString = "已取消";
                        break;
                    // 发送失败
                    case 5:
                        AgvStatus = 5;
                        AgvStatusString = "发送失败";
                        break;
                    // 运行中
                    case 6:
                        AgvStatus = 6;
                        AgvStatusString = "运行中";
                        break;
                    // 执行失败
                    case 7:
                        AgvStatus = 7;
                        AgvStatusString = "执行失败";
                        break;
                    // 已完成
                    case 8:
                        AgvStatus = 8;
                        AgvStatusString = "已完成";
                        break;
                    // 已下发
                    case 9:
                        AgvStatus = 9;
                        AgvStatusString = "已下发";
                        break;
                    // 等待确认
                    case 10:
                        AgvStatus = 10;
                        AgvStatusString = "等待确认";
                        break;
                }
                // 任务状态
                item.TaskState = AgvStatus;
                // 子任务序列
                item.SubTaskSeq = acceptDTO.subTaskSeq;
                // 子任务状态
                item.SubTaskStatus = acceptDTO.subTaskStatus;
                // 转发地址
                string forwardedEndpoint = App.GetOptions<ThirdServiceOptions>().TaskAPI.ToString();
                // 转发的数据
                AcceptForward acceptForward = new AcceptForward()
                {
                    TaskNo = acceptDTO.orderId,
                    TaskName = item.TaskName,
                    AssetNumber = acceptDTO.deviceCode,
                    AGVNo = item.AGVNo,
                    TaskState = AgvStatusString,
                    Priority = item.Priority,
                    ModelNo = item.ModelNo,
                    Source = item.Source,
                    Message = item.Message,
                    STime = item.STime,
                    ETime = item.ETime,
                    subTaskSeq = acceptDTO.subTaskSeq,
                };
                if (forwardedEndpoint == null)
                {
                    await _TaskEntity.InsertOrUpdateAsync(item);
                    return "上报成功";
                }
                else
                {
                    // TODO：转发
                    TransponderModel<AcceptForward> transponderModel = new TransponderModel<AcceptForward>();
                    transponderModel.ForwardData = acceptForward;
                    transponderModel.Timer = new Timer(RcsTimerCallback, transponderModel, 0, 5000);
                    // 将rcs得到的数据保存
                    await _TaskEntity.InsertOrUpdateAsync(item);
                    return "上报成功";
                }
            }
            catch (Exception ex)
            {
                // 错误信息
                throw Oops.Oh("错误：" + ex.Message);
            }
        }

        #endregion

        #region 获取AGV状态

        /// <summary>
        /// 获取AGV状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/ObtainAGVStatus")]
        [AllowAnonymous]
        [UnifyProvider("easygreat")]
        public async Task ObtainAGVStatus(List<ObtainAgvStatusModel> input)
        {
            #region 参数
            //{
            //    "payLoad":"0.0", 设备负载状态
            //    "devicePosition":"57540086", 设备当前位置
            //    "devicePostionRec":[  设备所在二维码的 x,y 坐标，前边的值是x，后边的是y
            //        4983,
            //        -6093
            //    ],
            //    "state":"InCharging",  设备状态
            //    "deviceCode":"CE35592BAK00001",  设备序列号
            //    "battery":"79",  电池电量
            //    "deviceName":"M001"  设备名称
            //}
            #endregion
            try
            {
                List<AgvStatusForward> agvStatusForwards = new List<AgvStatusForward>();
                string devicepostionrec = "";
                for (int i = 0; i < input.Count; i++)
                {
                    if (input[i].devicePostionRec == null)
                    {
                        devicepostionrec = 0.ToString();
                    }
                    else
                    {
                        // 将数组转换成string
                        devicepostionrec = string.Join(",", input[i].devicePostionRec);
                    }
                    InfoAgvEntity info = input[i].Adapt<InfoAgvEntity>();
                    info.devicePostionRec = devicepostionrec;
                    // 判断状态
                    switch (info.state)
                    {
                        case "Idle":
                            info.state = "空闲";
                            break;
                        case "Initializin":
                            info.state = "初始化中";
                            break;
                        case "InTask":
                            info.state = "任务中";
                            break;
                        case "Fault":
                            info.state = "故障";
                            break;
                        case "Offline":
                            info.state = "离线中";
                            break;
                        case "InCharging":
                            info.state = "充电中";
                            break;
                        case "InUpgrading":
                            info.state = "升级中";
                            break;
                        default:
                            break;
                    }
                    // 需要转发的数据
                    AgvStatusForward agvStatusForward = new AgvStatusForward()
                    {
                        CarNo = info.deviceName,
                        CarName = "",
                        CarStatus = info.state,
                        Battery = info.battery + "%",
                        BatteryCycle = null,
                        PayLoad = info.payLoad,
                        OfflineTime = null,
                        Position = info.devicePosition,
                        PostionRec = info.devicePostionRec,
                        AssetNumber = info.deviceCode,
                    };
                    // 添加到集合中
                    agvStatusForwards.Add(agvStatusForward);
                    // 查询是否已经有相同的数据
                    var agvinfo = await _InfoAgvEntity.GetFirstAsync(x => x.deviceCode == info.deviceCode);

                    if (agvinfo == null)
                    {
                        await _InfoAgvEntity.InsertAsync(info);
                    }
                    else
                    {
                        await _InfoAgvEntity.AsUpdateable()
                                            .SetColumns(it => new InfoAgvEntity
                                            {
                                                orderId = info.orderId,
                                                shelfNumber = info.shelfNumber,
                                                deviceStatus = info.deviceStatus,
                                                oritation = info.oritation,
                                                speed = info.speed,
                                                payLoad = info.payLoad,
                                                devicePosition = info.devicePosition,
                                                devicePostionRec = devicepostionrec,
                                                state = info.state,
                                                battery = info.battery,
                                                deviceName = info.deviceName,
                                                UpdateTime = DateTime.Now,
                                            })
                                            .Where(x => x.deviceCode == info.deviceCode)
                                            .ExecuteCommandAsync();
                    }
                }
                // 转发地址
                string forwardedEndpoint = App.GetOptions<ThirdServiceOptions>().TaskAPI.ToString();
                // 判断需不需要转发
                if (string.IsNullOrEmpty(forwardedEndpoint))
                {
                    return;
                }
                else
                {
                    TransponderModel<List<AgvStatusForward>> transponderModel = new TransponderModel<List<AgvStatusForward>>();
                    transponderModel.ForwardData = agvStatusForwards;
                    transponderModel.Timer = new Timer(AgvTimerCallback, transponderModel, 0, 5000);
                }


            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex);
            }
        }


        #endregion

        #region 报警消息上报

        /// <summary>
        /// 报警消息上报
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/AGV/Task/AlarmInformationReporting")]
        [AllowAnonymous]
        [UnifyProvider("easygreat")]
        public async Task AlarmInformationReporting(AlarmInformationModel input)
        {
            try
            {
                AlarmEntity data = new AlarmEntity()
                {
                    deviceNum = input.deviceNum,
                    deviceName = input.deviceName,
                    alarmDesc = input.alarmDesc,
                    alarmType = input.alarmType,
                    areaId = input.areaId,
                    alarmReadFlag = input.alarmReadFlag,
                    channelDeviceId = input.channelDeviceId,
                    alarmSource = input.alarmSource,
                    alarmGrade = input.alarmGrade,
                };
                long datetime = input.alarmDate.ToLong();
                // 将时间戳转化成日期格式
                DateTime times = DateTimeUtil.ToLocalTimeDateBySeconds(datetime);
                data.alarmDate = times;
                // 要转发的数据
                // 转发地址
                string forwardedEndpoint = App.GetOptions<ThirdServiceOptions>().TaskAPI.ToString();
                // 判断需不需要转发
                if (string.IsNullOrEmpty(forwardedEndpoint))
                {
                    await _AlarmEntity.InsertAsync(data);
                }
                else
                {
                    AlarmEntityForward alarmEntityForward = new AlarmEntityForward()
                    {
                        CarNo = input.deviceNum,
                        DlarmDesc = input.alarmDesc,
                        AlarmType = input.alarmType,
                        AreaId = input.areaId,
                        IsReadFlag = input.alarmReadFlag,
                        AlarmSite = input.channelDeviceId,
                        AlarmSource = input.alarmSource,
                        AlarmGrade = input.alarmGrade,
                        Proposal = input.channelName,
                        AddDate = times,
                        CarSerialNumber = input.deviceName,
                    };
                    TransponderModel<AlarmEntityForward> transponderModel = new TransponderModel<AlarmEntityForward>();
                    transponderModel.ForwardData = alarmEntityForward;
                    transponderModel.Timer = new Timer(AlarmTimerCallback, transponderModel, 0, 5000);
                    await _AlarmEntity.InsertAsync(data);
                }
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex);
            }
        }


        #endregion

        /// <summary>
        /// （RCS上报）定时器回调函数，用于处理转发请求
        /// </summary>
        /// <param name="state">参数</param>
        private static void RcsTimerCallback(object state)
        {
            // 这个方法将在每次定时器触发时执行
            // 强制转换状态对象为正确的类型  
            var transponderModel = (TransponderModel<AcceptForward>)state;
            // 增加重试次数并检查是否达到最大重试次数  
            if (transponderModel.retryCount < TransponderModel<AcceptForward>.MaxRetryCount)
            {
                transponderModel.retryCount++;
                Console.WriteLine($"请求失败，重试次数: {transponderModel.retryCount - 1}, 将再次尝试...");
            }
            else
            {
                // 达到最大重试次数，停止定时器并输出消息  
                transponderModel.Timer.Dispose();
                Console.WriteLine("已达到最大重试次数，定时器已停止。");
                return;
            }

            // 转发地址
            var forwardedEndpoint = App.GetOptions<ThirdServiceOptions>().TaskAPI.ToString();
            // 处理格式
            var forwardedContent = new StringContent(JsonConvert.SerializeObject(transponderModel.ForwardData), Encoding.UTF8, "application/json");
            using (var response = _HttpClient.PostAsync(forwardedEndpoint, forwardedContent).GetAwaiter().GetResult())
            {
                if (response.IsSuccessStatusCode)
                {
                    // 找到该方法的定时器，将其关闭
                    // 请求成功，停止定时器并输出消息  
                    transponderModel.Timer.Dispose();
                }
            }
        }

        /// <summary>
        /// （报警上报）定时器回调函数，用于处理转发请求
        /// </summary>
        /// <param name="state">参数</param>
        private static void AlarmTimerCallback(object state)
        {
            // 这个方法将在每次定时器触发时执行
            // 强制转换状态对象为正确的类型  
            var transponderModel = (TransponderModel<AlarmEntityForward>)state;
            // 增加重试次数并检查是否达到最大重试次数  
            if (transponderModel.retryCount < TransponderModel<AlarmEntityForward>.MaxRetryCount)
            {
                transponderModel.retryCount++;
                Console.WriteLine($"请求失败，重试次数: {transponderModel.retryCount - 1}, 将再次尝试...");
            }
            else
            {
                // 达到最大重试次数，停止定时器并输出消息  
                transponderModel.Timer.Dispose();
                Console.WriteLine("已达到最大重试次数，定时器已停止。");
                return;
            }
            // 转发地址
            var forwardedEndpoint = App.GetOptions<ThirdServiceOptions>().AlarmAPI.ToString();
            // 处理格式
            var forwardedContent = new StringContent(JsonConvert.SerializeObject(transponderModel.ForwardData), Encoding.UTF8, "application/json");
            using (var response = _HttpClient.PostAsync(forwardedEndpoint, forwardedContent).GetAwaiter().GetResult())
            {
                if (response.IsSuccessStatusCode)
                {
                    // 找到该方法的定时器，将其关闭
                    // 请求成功，停止定时器并输出消息  
                    transponderModel.Timer.Dispose();
                }
            }
        }

        /// <summary>
        /// （AGV设备上报）定时器回调函数，用于处理转发请求
        /// </summary>
        /// <param name="state">参数</param>
        private static void AgvTimerCallback(object state)
        {
            // 这个方法将在每次定时器触发时执行
            // 强制转换状态对象为正确的类型  
            var transponderModel = (TransponderModel<List<AgvStatusForward>>)state;
            // 增加重试次数并检查是否达到最大重试次数  
            if (transponderModel.retryCount < TransponderModel<List<AgvStatusForward>>.MaxRetryCount)
            {
                transponderModel.retryCount++;
                Console.WriteLine($"请求失败，重试次数: {transponderModel.retryCount - 1}, 将再次尝试...");
            }
            else
            {
                // 达到最大重试次数，停止定时器并输出消息  
                transponderModel.Timer.Dispose();
                Console.WriteLine("已达到最大重试次数，定时器已停止。");
                return;
            }
            // 转发地址
            var forwardedEndpoint = App.GetOptions<ThirdServiceOptions>().InfoAPI.ToString();
            // 处理格式
            Console.WriteLine(JsonConvert.SerializeObject(transponderModel.ForwardData));
            var forwardedContent = new StringContent(JsonConvert.SerializeObject(transponderModel.ForwardData), Encoding.UTF8, "application/json");
            var response = _HttpClient.PostAsync(forwardedEndpoint, forwardedContent).GetAwaiter().GetResult();
            if (response.IsSuccessStatusCode)
            {
                // 找到该方法的定时器，将其关闭
                // 请求成功，停止定时器并输出消息  
                transponderModel.Timer.Dispose();
                Console.WriteLine("请求成功，已转发成功！");
            }

        }
    }
}
